﻿using ApiLib.AppStart;
using ApiLib.Common.Attributes;
using ApiLib.Models;
using Microsoft.AspNetCore.Mvc;

namespace ApiLib.Controllers;

/// <summary>
/// 表格
/// </summary>
[ApiDescriptionSettings(GlobalConstants.ApiDescriptionSettings)]
public class TableController : BaseController
{
    /// <summary>
    /// 保存表
    /// </summary>
    /// <returns></returns>
    public bool TableSave(SysTableInfo info)
    {
        if (!info.IsFolder)
        {
            if (info.FieldInfos == null || !info.FieldInfos.Any())
            {
                throw ActionException("没有字段信息");
            }

            if (info.FieldInfos.GroupBy(fieldInfo => fieldInfo.FieldName)
                .Any(group => group.Count() > 1))
            {
                throw ActionException("字段名称不能重复");
            }
        }

        InitAddAndUpdate(info);
        info.DbTableSync(Db);
        return true;
    }

    /// <summary>
    /// 删除表
    /// </summary>
    /// <param name="id">表id</param>
    /// <returns></returns>
    public bool TableDelete(int id)
    {
        var table = Db.Queryable<SysTableInfo>().Single(info => info.Id == id);
        if (table == null)
        {
            throw ActionException("组件不存在！");
        }

        if (BaseUser == null || table.TableType == "System" || table.CreateUser != BaseUser.GetSid())
        {
            throw ActionException("权限不足！");
        }

        return Db.Deleteable(table).ExecuteCommand() > 0;
    }


    /// <summary>
    /// 表列表
    /// </summary>
    /// <returns></returns>
    public List<SysTableInfo> TableList(int parent = 0)
    {
        var lists = Db.Queryable<SysTableInfo>()
            .WhereIF(parent != -1, info => info.ParentId == parent)
            .ToList();
        return lists;
    }

    /// <summary>
    /// 表信息
    /// </summary>
    /// <returns></returns>
    public SysTableInfo TableInfo(int id)
    {
        var sysTableInfo = Db.Queryable<SysTableInfo>().InSingle(id);
        if (sysTableInfo == null)
        {
            throw ActionException("找不到");
        }

        return sysTableInfo;
    }
}